package com.saianfu.flowable.demo.common.impl

import com.saianfu.flowable.demo.common.ActHistTaskQuery
import org.flowable.engine.HistoryService
import org.flowable.task.api.history.HistoricTaskInstance
import org.flowable.task.api.history.HistoricTaskInstanceQuery
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

/**
 * 历史任务
 *
 * @author liuxz
 * @date 2019/08/30
 */
@Component
class HistTaskQueryHandler : ActHistTaskQuery {
    @Autowired
    lateinit var historyService: HistoryService

    override fun createHistoricTaskInstanceQuery(): HistoricTaskInstanceQuery {
        return historyService.createHistoricTaskInstanceQuery()
    }

    override fun activeTask(instanceId: String): HistoricTaskInstance {
        return createHistoricTaskInstanceQuery().processInstanceId(instanceId).unfinished().singleResult()
    }

    override fun finishedTask(taskId: String): HistoricTaskInstance {
        return createHistoricTaskInstanceQuery().taskId(taskId).singleResult()
    }

    override fun listByInstanceId(instanceId: String): List<HistoricTaskInstance> {
        return createHistoricTaskInstanceQuery().processInstanceId(instanceId).orderByTaskCreateTime().desc().list()
    }

    override fun pageListByInstanceId(instanceId: String, start: Int, limit: Int): List<HistoricTaskInstance> {
        return createHistoricTaskInstanceQuery()
                .processInstanceId(instanceId)
                .orderByTaskCreateTime()
                .desc().listPage(start, limit)
    }

    companion object {
        protected var logger = LoggerFactory.getLogger(HistTaskQueryHandler::class.java)
    }
}